// xc_lshop/savemoney/recharge/index.js
var order_bill = require('../../model/htrecharge')
var app = getApp();

Page({
  mixins: [require('../../../../xc/mixins/basicMixin')],

  /**
   * 页面的初始数据
   */
  data: {
    payloading: false,
    keyval: "phonecharges",
    xcmodel: {
      type: 1,
    },
    rechargeconfig:null
  },
  xcloaddata: function (options, config) {
    if (options.key) {
      this.setData({
        keyval: options.key
      })
    }
    if (config['htrechargeconfig'] && config['htrechargeconfig']['basic']['status'] == 1) {
      // console.log("config['rechargeconfig']")
      // console.log(config['rechargeconfig'])
      this.setData({
        rechargeconfig: config['htrechargeconfig']
      })
    } else {
      // this.error("充值未配置", true)
      this.pageback()
    }
  },
  createorder(e) {
    console.log("createorder")
    console.log(e)
    if(e.detail){
      this.setData({
        xcmodel:e.detail
      })
    }
   

    var that = this;

    app.xc_sys_config.authop.oppower("login").then(function (res) {
 
      if (res['status'] == 1) {
        that.setData({
          member: res['obj']
        })
        app.globalData.member = res['obj']
        var res = that.valide();
        if (res) {
          var formdata = that.data.xcmodel
        
          var  tip = "手机号：" + formdata.mobile + "\n充值面值："+ formdata.name + "\n实付金额："+ formdata.realprice 
        
          wx.showModal({
            title: "确认充值",
            content: tip,
            cancelColor: 'cancelColor',
            success: function (e) {
              if (e.confirm) {
                var template_ids = that.data.rechargeconfig['template_ids'];
                that.showtemplate(template_ids, formdata)

                // that.postorder(formdata)
              }
              // 
            }
          })
        }

      }
    })

  },
  postorder(formdata) {
    console.log("formdata")
    console.log(formdata)
    var that = this
    that.setData({
      payloading: true
    })

    formdata['keyval'] = that.data.keyval
    order_bill.createorder(formdata).then(function (restmodel) {

      if (restmodel["status"] == 1) {
        //  template_ids=["SumpUZ0J0kB_jQ3uFhgfxcYjCngZPP45yHPpnFxcKWs","1uZEExJ1levUgB2hFlGFox6mWdxkIFAil8fSQkUxLY8","EYmkv8o3hh9Mugu4YNhDP2zbnpdYpawWghaaOSPlOyI"]
        if (restmodel["paytype"] == 1) {
          var pay_params = restmodel["pay_params"];
          wx.requestPayment({
            timeStamp: pay_params["timeStamp"],
            nonceStr: pay_params["nonceStr"],
            package: pay_params["package"],
            signType: pay_params['signType'],
            paySign: pay_params["paySign"],
            success(res) {

              order_bill.queryorder(restmodel["id"]).then(function (queryreslut) {
                if (queryreslut["status"] == 1) {
                  // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])
                  wx.redirectTo({
                    url: '/xc_lshop/shop/paycore/paysuccess?id=' + restmodel["id"],
                  })
                  that.setData({
                    payloading: false
                  })
                }
              })
            },
            fail(res) {
          
              if (res["errMsg"] == "requestPayment:fail cancel") {
                wx.showModal({
                  title: '订单未支付',
                  content: '订单未支付',
                  showCancel: false,
                  success(res) {
                    // console.log("wx.redirectTo959595959")
                    that.setData({
                      payloading: false
                    })
                    wx.redirectTo({
                      url: "/xc_lshop/shop/order/index",
                    })
                  }
                })
              }
            }
          })
        } else if (restmodel["paytype"] == 0) {
          // console.log("33333333333333333333")
          // var myDate = new Date();
          // var now=  myDate.getMinutes() +":" + myDate.getSeconds(); 
          wx.redirectTo({
            url: '/xc_lshop/shop/paycore/paysuccess?id=' + restmodel["id"],
          })
          // console.log(now)
          // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])
          that.setData({
            payloading: false
          })
        }
      } else {
        wx.showModal({
          title: '错误',
          content: restmodel["message"],
        })
        that.setData({
          payloading: false
        })
      }
    })
  },
  showtemplate(template_ids, formdata) {
    var that = this;
    if (template_ids && template_ids.length > 0) {
      if (template_ids.length > 3) {
        template_ids = template_ids.slice(0, 3)
      }
      wx.requestSubscribeMessage({
        tmplIds: template_ids,
        success(res) {
         

        },
        fail(res) {
          

        },
        complete(res) {
       
         
          that.postorder(formdata)
        }
      })
    } else {
      that.postorder(formdata)
      
    }
  },
  sendnotice_buy(ordernum) {
    order_bill.sendnotice_buy(ordernum).then(function (restmodel) {
      console.log(restmodel)
    })
  },
  valide() {
    var formdata = this.data.xcmodel;
    var message = "";
 
    if (!formdata.id) {
      message = "请选择充值项目;";
    }
    if (!formdata.mobile) {
        message = "请输入充值手机号码;";
    }
 
    if (message) {
      wx.showModal({
        title: "错误",
        content: message,
      })
      return false;
    } else {
      return true;
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onClickKey(e) {
    var keyval = e.currentTarget.dataset.key;
    this.setData({
      keyval: keyval
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})